/*
 * @Descripttion: 出手鸭小程序
 * @version:1.0.1 
 * @Author: HHL
 * @Date: 2022-11-29 17:55:49
 * @LastEditTime: 2025-07-03 09:56:15
 * @LastEditors: sueRimn
 */


import store from '@/store'
import qs from 'qs'

// 拨打电话
export const callPhone = (phone) => {
  if (!phone) { return }
  uni.makePhoneCall({ phoneNumber: phone })
}

/// 设置变量到缓存中去，返回设置缓存结果，true成功，false失败。
export function setExpData(key, value, expires) {
  if (expires > 0) {
    expires = Date.parse(new Date()) + expires * 1000;
  }
  let data = { "value": value, "expires": expires };
  let resData = uni.setStorageSync(key, JSON.stringify(data));
  let storageList = uni.getStorageSync("storageList") || [];
  if (JSON.stringify(storageList).indexOf(key) == -1) {
    storageList.push({ "key": key, "expires": expires });
    uni.setStorageSync("storageList", storageList);
  }


  return resData;
}

/// 获取缓存数据，只能获取常规类型
export function getExpData(key) {
  let resData = uni.getStorageSync(key);
  let data = { "value": "", "expires": 0 };
  if (resData == null) {
    return null;
  }
  try {
    data = JSON.parse(resData);
  } catch (e) {
    return null;
  }

  let expires = data["expires"];
  if (expires > 0) {
    let nowTimes = Date.parse(new Date());
    if (expires < nowTimes) {
      uni.removeStorageSync(key);
      return null;
    }
  }
  return data["value"];
}
//每次启动删除过期缓存
export function clearExpData() {
  let storageList = uni.getStorageSync("storageList") || [];
  let storageNowList = [];
  for (let i = 0; i < storageList.length; i++) {
    let data = storageList[i];
    let nowTimes = Date.parse(new Date());
    if (data.expires < nowTimes) {
      uni.removeStorageSync(data.key);
    } else {
      storageNowList.push(data);
    }
  }
  uni.setStorageSync("storageList", storageNowList);
}

//删除定时缓存
export function clearExpList() {
  let storageList = uni.getStorageSync("storageList") || [];
  let storageNowList = [];
  for (let i = 0; i < storageList.length; i++) {
    let data = storageList[i];
    uni.removeStorageSync(data.key);
  }
  uni.setStorageSync("storageList", []);
}

// 隐藏手机号中间四位
export function hidePhoneNumber(str) {
  if (!str || typeof str !== 'string') {
    return ''
  }
  // #ifdef MP-ALIPAY
  return `${str.substr(0, 3)}******${str.substr(9)}`
  // #endif

  // #ifndef MP-ALIPAY
  return `${str.substr(0, 3)}****${str.substr(7)}`
  // #endif
}


// 日历补全零`
export function fillZero(num) {
  return num < 10 ? `0${num}` : num
}
// 日历去掉零
export function removeZero(str) {
  return str[0] === '0' ? str.substr(1) : str
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}


//按数组替换
export function array_replace(str, arr) {
  var reg = new RegExp(arr.join('|'), 'g');
  str = str.replace(reg, "");
  return str;
}

//解析支付宝URL
export function resolvAlipayUrl(url) {
  url = unescape(url)
  let appId = "";
  let page = "";
  let extraData = {};
  var reg = /appId=(.*)/
  if (url.indexOf("page") > -1) {
    reg = /appId=(.*)&page=(.*)/
    if (url.indexOf("&query") > -1) {
      reg = /appId=(.*)&page=(.*)&query=(.*)/
    }
  }
  const urlArr = reg.exec(url)
  // console.log(urlArr)
  if (urlArr[1]) {
    appId = urlArr[1]
  }
  if (urlArr[2]) {
    page = urlArr[2]
  }
  if (urlArr[3]) {
    var extraStr = urlArr[3]
    var extraStrBefore = extraStr.split('&')
    for (let i = 0; i < extraStrBefore.length; i++) {
      var extraStrBeforeSub = extraStrBefore[i]
      var extraIndex = extraStrBeforeSub.indexOf("=")
      var extraParams = extraStrBeforeSub.split('=')
      var key = extraStrBeforeSub.substr(0, extraIndex)
      var value = extraStrBeforeSub.substr(extraIndex + 1, extraStrBeforeSub.length)
      extraData[key] = value
    }
  }
  let alipayParams = {
    appId: appId,
    page: page,
    extraData: extraData
  }
  return alipayParams;
}

/**
 * 链接跳转判断
 * @param routeType 跳转方式：0-不跳转 1-小程序内页 2-外部网页 3-商品详情页 4-主题 5-外部小程序 6-导购
 */
export const urlJump = ({ routeType, target }) => {
  console.log(routeType, target)

  if (routeType == 1 && target) {
    let paramsObj = {}
    if (target.indexOf("?") != -1) {
      const arr = target.split("?")
      paramsObj = qs.parse(arr[1]);
      if (paramsObj.referer) {
        store.dispatch('user/updateReferer', paramsObj.referer)
      }
    }

    if (
      target.indexOf('pages/index/index') !== -1 ||
      target.indexOf('pages/user/index') !== -1
    ) {
      uni.switchTab({ url: target })
    } else {
      console.log('跳转到小程序内页', target)
      uni.navigateTo({ url: target })
    }
  }
  if (routeType == 2 && target) {
    // #ifdef H5
    window.location.href = target
    // #endif

    // #ifndef H5
    uni.navigateTo({ url: `/pages/webview/index?url=${target}` })
    // #endif
  }
  if (routeType == 3 && target) {
    uni.navigateTo({ url: `/pages/product/index?id=${target}` })
  }

  if (routeType == 5 && target) {

    // #ifdef MP-ALIPAY
    if (target.indexOf("http") === 0) {
      my.ap.openURL({ url: target })
      return
    }
    // #endif

    const urlArr = resolvAlipayUrl(target)

    const extraData = urlArr['extraData']

    if (extraData.referer) {
      store.dispatch('user/updateReferer', extraData.referer)
    }

    uni.navigateToMiniProgram({
      appId: urlArr['appId'],
      path: urlArr['page'],
      extraData,
    })
  }
}

// 显示提示语
export const waitShowToast = (title, wait = 100, duration = 2000) => {
  setTimeout(() => {
    uni.showToast({
      title,
      icon: 'none',
      duration,
    })
  }, wait)
}

export const wait = (time = 500) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}


// 复制对象
export function copyObject(obj) {
  return JSON.parse(JSON.stringify(obj))
}

// 组合标签
export function mergeReferer(referer) {
  const fromreferer = uni.getStorageSync('fromreferer')

  if (fromreferer && referer) {
    if (fromreferer === referer) { return referer }
    return `${fromreferer}__${referer}`
  }

  if (fromreferer && !referer) {
    return fromreferer
  }

  return referer
}

//生成上门时间
export function generateVisitTime(time) {
  let dayMultiArray = ["0", "1", "2", "3", "4", "5"]
  let hourMultiArray = ["08", "10", "12", "14", "16", '18']
  const multiArray = [

  ]
  const date = new Date()
  let hours = date.getHours()
  let todayMultiArray = []
  //根据当前小时匹配hourMultiArray
  for (let i = 0; i < hourMultiArray.length; i++) {
    if (hours < hourMultiArray[i] && hours < 18) {
      todayMultiArray.push(hourMultiArray[i])
    }
  }

  //生成数据
  for (let i = 0; i < dayMultiArray.length; i++) {
    let _hourMultiArray = hourMultiArray
    if (i == 0) {
      _hourMultiArray = todayMultiArray
    }
    if (_hourMultiArray.length > 0) {
      multiArray.push({
        "day": new Date(new Date().toLocaleDateString()).getTime() + (i * 86400000),
        "hour": _hourMultiArray
      })
    }
  }
  return multiArray
}

//Maptostr
export function mapToStr(value) {
  let _value = "";
  for (let key in value) {
    _value += "_" + key + "_" + value[key]
  }
  return _value;
}
